package com.whosly.demo.jmh.size;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @author fengyang
 * @date 2023/7/2 下午9:35
 * @see <a href="fengyang@stoneatom.com">mailTo: fengyang@stoneatom.com</a>
 */
public class ByteCopy
{
    public static String systemCopy(byte[] byteReq) {
        byte[] newBytes = new byte[byteReq.length];
        System.arraycopy(byteReq, 0, newBytes, 0, byteReq.length);

        newBytes = new byte[byteReq.length];
        System.arraycopy(byteReq, 0, newBytes, 0, byteReq.length);

        String reqVal = new String(newBytes);

        return reqVal;
    }

    public static String zeroCopy(byte[] byteReq) {
        ByteBuf zeroByteBuf = Unpooled.wrappedBuffer(byteReq);
        byte[] mergeDataAssemblyHeader = new byte[zeroByteBuf.readableBytes()];
        zeroByteBuf.readBytes(mergeDataAssemblyHeader);

        String reqVal = new String(mergeDataAssemblyHeader);

        return reqVal;
    }

    public static byte[] read(ByteBuf in) {
        // 由于ByteBuf是使用了DirectBuffer，所以不支持array()的操作
        byte[] data;
        if (in.isDirect()) {
            // 此处表明是堆外内存.
            data = new byte[in.readableBytes()];
            in.readBytes(data);
        } else {
            // 堆内
            // data will not be accessed any more,so we can use this array safely
            data = in.readBytes(in.readableBytes()).array();
        }
        if (data == null) {
            return null;
        }

        return data;
    }

}
